<?php

namespace App\Notifications\Channels;

use Illuminate\Support\Facades\Cache;
use Illuminate\Notifications\Notification;

/**
 * 企业微信发送通知
 * @package App\Notifications\Channels
 */
class QyWx
{
    const ACCESS_TOKEN_URL = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken';
    const MESSAGE_SEND_URL = 'https://qyapi.weixin.qq.com/cgi-bin/message/send';
    const CORPID = 'ww98d3a56cee4ba151';
    const CORPSECRET = 'M_-Ux66oXsTVmoeHhjKCHsXcTY24yjUQJKiLU2DeEeI';

    /**
     * 发送给定通知.
     *
     * @param mixed $notifiable
     * @param $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        $access_token = $this->getAccessToken();
        $post_data = $notification->toQyWx();
        $this->http_post(self::MESSAGE_SEND_URL . '?access_token=' . $access_token, json_encode($post_data, JSON_UNESCAPED_UNICODE));
    }

    function http_post($url, $post_data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        if ($output === false) {
            return json_encode(array('error' => curl_errno($ch)));
        }

        curl_close($ch);
        return $output;
    }

    private function getAccessToken()
    {
        $qywx_account = Cache::remember('access_token', now()->addMinutes(60), function () {
            $param['corpid'] = self::CORPID;
            $param['corpsecret'] = self::CORPSECRET;
            $query_string = http_build_query($param);
            $access_token_url = self::ACCESS_TOKEN_URL . '?' . $query_string;
            $result = json_decode(file_get_contents($access_token_url));
            if ($result->errcode == 0) {
                return $result->access_token;
            } else {
                //接口调用出错
                throw  new \Exception('access_token获取失败');
            }
        });

        return $qywx_account;
    }
}
